package com.spica.spicaschool.ui.explore

import android.annotation.SuppressLint
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.drakeet.multitype.MultiTypeAdapter
import com.fondesa.recyclerviewdivider.dividerBuilder
import com.spica.spicaschool.base.BaseFragment
import com.spica.spicaschool.base.ILoadMoreAdapter
import com.spica.spicaschool.base.LoadMoreAdapterWrapper
import com.spica.spicaschool.bean.news.News
import com.spica.spicaschool.component.WrapContentLinearLayoutManager
import com.spica.spicaschool.databinding.LayoutRecycleviewBinding
import com.spica.spicaschool.viewmodel.NewsViewModel
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
import java.util.concurrent.atomic.AtomicInteger

/**
 * 体育新闻列表
 */
@AndroidEntryPoint
class ExploreFragment : BaseFragment<LayoutRecycleviewBinding>(), ILoadMoreAdapter,
  LoadMoreAdapterWrapper.OnClickRetryListener {

  private var isOk = false // 是否完成View初始化

  private var isFirst = true // 是否为第一次加载

  private var isError = false

  private var isLoading = false

  private var page = AtomicInteger(1)

  private val items = mutableListOf<News>()

  private lateinit var adapter: MultiTypeAdapter

  private val viewModel: NewsViewModel by viewModels()

  override fun setupViewBinding(
    inflater: LayoutInflater,
    container: ViewGroup?
  ): LayoutRecycleviewBinding = LayoutRecycleviewBinding.inflate(layoutInflater, container, false)


  override fun init() {
    adapter = MultiTypeAdapter(items)
    adapter.register(NewsDelegate(requireActivity()))
    adapter.setHasStableIds(true)
    viewBinding.rvList.layoutManager =
      WrapContentLinearLayoutManager(requireContext())
    viewBinding.rvList.adapter = LoadMoreAdapterWrapper(
      requireContext(),
      adapter, this,
      this
    )

    requireContext()
      .dividerBuilder()
      .size(8, TypedValue.COMPLEX_UNIT_DIP)
      .asSpace()
      .showLastDivider()
      .showFirstDivider()
      .build()
      .addTo(viewBinding.rvList)

    viewBinding.layoutSwipe.setOnRefreshListener {
      onLoadData(isRefresh = true)
    }

    isOk = true

  }

  /**
   * 加载数据
   * isRefresh：是否刷新
   **/
  @SuppressLint("NotifyDataSetChanged")
  private fun onLoadData(isRefresh: Boolean) {
    isLoading = true
    if (isRefresh) {
      isError = false
      items.clear()
      page.set(1)
    }
    viewModel.pageChanged(page.getAndAdd(1))
  }

  override fun onResume() {
    super.onResume()
    initLoadData()
  }

  @SuppressLint("NotifyDataSetChanged")
  private fun initLoadData() {
    if (isOk && isFirst) {
      viewModel.fetchNews(
        onError = {
          isError = true
          Timber.e("请求过程发生错误：$it")
        },
        onComplete = {
          isLoading = false
          Timber.e("请求结束")
          viewBinding.layoutSwipe.isRefreshing = false
        })
    }
    viewModel.newsLiveData.observe(this) {
      viewBinding.root.post {
        if (it != null)
          items.addAll(it)
        adapter.notifyDataSetChanged()
      }
    }
  }

  // 加载更多
  private fun onLoadMore() {
    onLoadData(false)
  }

  override fun hasMoreResults(): Boolean = false

  override fun hasError(): Boolean = isError

  override fun isLoading(): Boolean = isLoading

  override fun onClickRetry() {
    Timber.e("加载更多...")
    onLoadMore()
  }


}
